var activePopup = null;

function openPopup(pageName, properties, params) {
    jQuery.ajax(generateRequestedUrl({
        page : pageName,
        params : params
    }), {
        type : "post",
        dataType : "html",
        data : (properties ? properties.extraParams : {}),
        success : function(result) {
            var props = {
                width : 300,
                height : 200
            };
            for (var prop in properties) {
                props[prop] = properties[prop];
            }
            jQuery("#popup").html(result);
            jQuery("#popup").dialog({
                width : props.width,
                height : props.height,
                modal : true,
                title : properties.title
            });
            popupOpened(properties.extraParams.popup_id);
        }
    });
}

function formatNumbers(numberIn) {
    if (isNaN(parseInt(numberIn, 10))) { return numberIn; }
    var result = "";
    var number = "" + numberIn;
    number = number.split(".")[0];
    var ctr = 0;
    for (var i = number.length-1; i >= 0; i--) {
        ctr++;
        result = number.charAt(i) + result;
        if (ctr % 3 == 0 && i > 0) {
            result = "," + result;
        }
    }
    return result;
}

function openAdminPopup(pageName, subpageName, properties, params) {
    jQuery.ajax(generateAdminRequestedUrl({
        page : pageName,
        params : params,
        subpage : subpageName
    }), {
        type : "post",
        dataType : "html",
        data : (properties ? properties.extraParams : {}),
        success : function(result) {
            var props = {
                width : 300,
                height : 200
            };
            for (var prop in properties) {
                props[prop] = properties[prop];
            }
            jQuery("#popup").html(result);
            jQuery("#popup").dialog({
                width : props.width,
                height : props.height,
                modal : true,
                title : properties.title
            });
            popupOpened(properties.extraParams.popup_id);
        }
    });
}

function openlink(item) {
    var url = jQuery(item).attr("title");
    window.open(url, "_blank", "width=1000, height=290, scrollbars=1");
}

var loadedPages = {};

function pageLoaded(pageName) {
    if (loadedPages[pageName]) { return true; }
    return false;
}

function displayLargeImage(imgItem) {
    jQuery("div#imgviewer").html("<img src='" + imgItem.src.replace(/\&\_thumbnail=1/g, "") + "' width=900>")
    .css({
        position : "fixed",
        top : 100,
        left : 100
    });
    jQuery("div#imgviewer").show("fade", {}, 300);
    jQuery("div#modal").show("fade", {}, 300);
}

function closeImgViewer() {
    jQuery("div#imgviewer").hide("fade", {}, 300);
    jQuery("div#modal").hide();
}

function getPageHtml(pageName, isAdmin, destinationId) {
    jQuery.ajax(generateRequestedUrl({
        page : pageName,
        mode : (isAdmin ? "admin" : "normal")
    }), {
        type : "post",
        dataType : "html",
        data : (properties ? properties.extraParams : {}),
        success : function(result) {
            loadedPages[pageName] = true;
            jQuery("#" + destinationId).html(result);
        }
    });
}

var displayTimer = null;
function displayMessage(messageType, messageText) {
    jQuery("div#message_container").empty();
    jQuery("div#message_container").append(
        jQuery("<div>")
            .addClass("ui-widget")
            .append(
                jQuery("<div>")
                    .addClass("ui-corner-all")
                    .addClass((messageType == "error" ? "ui-state-error" : "ui-state-highlight"))
                    .css({ "padding" : "0 .7em"})
                    .append(
                        jQuery("<p>")
                            .append(
                                jQuery("<span>")
                                    .addClass("ui-icon")
                                    .addClass((messageType == "error" ? "ui-icon-alert" : "ui-icon-info"))
                                    .css({"float" : "left", "margin-right" : ".3em"})
                            )
                            .append(
                                jQuery("<strong>")
                                    .text("Error: ")
                            )
                            .text(messageText)
                    )
            )
            .show("fade", {}, 300)
    );
    if (displayTimer != null) {
        clearTimeout(displayTimer);
    }
    displayTimer = setTimeout(function() {
        jQuery("div#message_container div.ui-widget").hide("fade", {}, 300);
    }, 5000);
}

function getHS2FromHS4(hs4) {
    if (hs4.length >= 4) {
        return hs4.substring(0, 2);
    } else if (hs4.length == 3) {
        return hs4.substring(0, 1);
    } else {
        return hs4;
    }
}

function popupOpened(id) {
    try {
        eval(id + "_open()");
    }
    catch (e) {
    }
}

function setPopupResult(data) {
    popupResult = data;
}

function closePopup() {
    jQuery("#popup").dialog("close");
}

function callService(pageName, serviceName, params, callbacks) {
    jQuery.ajax("index.php?mode=service&page=" + pageName + "&service=" + serviceName, {
        data : params,
        type : "POST",
        dataType : "json",
        success : function(result) {
            if (result.success) {
                callbacks.success(result.data);
            } else {
                callbacks.failure(result.errorCode, result.msg);
            }
        },
        failure : function() {
            callbacks.failure(1, "The requested service is not available!");
        }
    });
}

function callAdminService(pageName, serviceName, params, callbacks) {
    jQuery.ajax("index.php?mode=adminservice&page=" + pageName + "&service=" + serviceName, {
        data : params,
        type : "POST",
        dataType : "json",
        success : function(result) {
            if (result.success) {
                callbacks.success(result.data);
            } else {
                callbacks.failure(result.errorCode, result.msg);
            }
        },
        failure : function() {
            callbacks.failure(1, "The requested service is not available!");
        }
    });
}

function openOverlay(width, height, content, closable) {
    if (closable === undefined) { closable = true; }
    jQuery("body").append(
        jQuery("<div>")
            .attr("id", "overlay_shadow")
            .addClass("ui-overlay")
            .append(
                jQuery("<div>")
                    .addClass("ui-widget-overlay")
            ).append(
                jQuery("<div>")
                    .addClass("ui-widget-shadow")
                    .addClass("ui-corner-all")
                    .css({
                        width : width + 10,
                        height : height + 10,
                        position : "absolute",
                        left : 100,
                        top : 100
                    })
            )
            .show("fade", {}, 300)
    );
    jQuery("body").append(
        jQuery("<div>")
            .css({
                width : width,
                height : height,
                position : "absolute",
                left : 105,
                top : 105
            })
            .attr("id", "overlay")
            .addClass("ui-widget")
            .addClass("ui-widget-content")
            .addClass("ui-corner-all")
            .append(
                jQuery("<p>")
                    .html(content)
            )
            .show("fade", {}, 300)
    );
    if (closable) {
        jQuery(window).keyup(function(ev) {
            if (ev.keyCode == 27) {
                closeOverlay();
            }
        });
    }
}

function closeOverlay() {
    jQuery("div#overlay_shadow").hide("fade", {}, 300).empty().remove();
    jQuery("div#overlay").hide("fade", {}, 300).empty().remove();
}

function callHtmlService(pageName, serviceName, params, callbacks) {
    jQuery.ajax("index.php?mode=service&page=" + pageName + "&service=" + serviceName, {
        data : params,
        type : "POST",
        dataType : "html",
        success : function(result) {
            callbacks.success(result);
        },
        failure : function() {
            callbacks.failure(1, "The requested service is not available!");
        }
    });
}

function callHtmlAdminService(pageName, serviceName, params, callbacks) {
    jQuery.ajax("index.php?mode=adminservice&page=" + pageName + "&service=" + serviceName, {
        data : params,
        type : "POST",
        dataType : "html",
        success : function(result) {
            callbacks.success(result);
        },
        failure : function() {
            callbacks.failure(1, "The requested service is not available!");
        }
    });
}

function callServiceS(pageName, serviceName, params) {
    var result;
    jQuery.ajax("index.php?mode=service&page=" + pageName + "&service=" + serviceName, {
        data : params,
        async : false,
        type : "POST",
        dataType : "json",
        success : function(res) {
            if (res.success) {
                result = res.data;
            }
        }
    });
    return result;
}

function submitForm(formName, waitMsg, buttonItem) {
    var waitMsg = (waitMsg === undefined ? "Submitting form, please wait" : waitMsg);
    var url = jQuery("form[name='" + formName+"']").attr("action");
    var allowed = true;
    jQuery("form[name='" + formName + "'] div").each(function(ndx, item) {
        if (jQuery(item).hasClass("invalid")) {
            allowed = false;
        }
    });
    if (!allowed) { return; }
    params = {};
    jQuery("form[name='" + formName + "'] input").each(function(ndx, item) {
        if (item.type == "text" || item.type == "password" || item.type == "hidden") {
            if (jQuery(item).hasClass("impex_choice")) {
                return;
            } else {
                params[item.name] = item.value;
            }
        } else if (item.type == "radio" || item.type == "checkbox") {
            if (item.checked) { params[item.name] = item.value; }
        }
    });
    jQuery("form[name='" + formName + "'] select").each(function(ndx, item) {
        params[item.name] = item.value;
    });
    jQuery("form[name='" + formName + "'] textarea").each(function(ndx, item) {
        params[item.name] = item.value;
    });
    var tbl;
    if (buttonItem) {
        tbl = jQuery(buttonItem).parents("table").first();
    } else {
        tbl = jQuery("form[name='" + formName + "'] button[type='submit']").parents("table").first();
    }
    tbl.find("td").last().append(
        jQuery("<div>").html("<img src='site/resources/img/icons/ajax-loader.gif' style='display:inline;margin-right:10px;'>" + waitMsg)
    );
    jQuery.ajax(url, {
        data : params,
        type : "POST",
        dataType : "json",
        success : function(res) {
            tbl.find("td").last().empty().append(
                jQuery("<div>").text("Form submitted")
            );
            setTimeout(function() {
                tbl.find("td").last().find("div").hide("fade", {}, 300);
            }, 3000);
            if (res.type == "validation") {
                if (!res.overall) {
                    displayFormErrors(res.msgArray);
                }
            }
            if (res.success) {
                jQuery("div.form_errors").hide("fade", {}, 300);
                if (res.redirect) {
                    window.location= generateRequestedUrl(res.redirect);
                }
            } else if (res.success === 0) {
                displayFormErrors([{code : 0, msg : res.msg}]);
            }
        }
    });
}

function hideFormErrors() {
    jQuery("input.error").removeClass("error");
    jQuery("div.form_errors").hide("fade", {}, 300);
    jQuery("div.form_errors ul").empty();
}

function displayFormErrors(msgArray) {
    jQuery("input.error").removeClass("error");
    jQuery("div.form_errors ul").empty();
    jQuery("div.form_errors").show("fade", {}, 300);
    var codes = [];
    for (var fld in msgArray) {
        jQuery("input[name='" + fld + "']").addClass("error");
        if (!codes.exists(msgArray[fld].code)) {
            jQuery("div.form_errors ul").append(jQuery("<li>")
                .html(msgArray[fld].msg)
            );
            codes.push(msgArray[fld].code);
        }
    }
}

function redirect(page, subpage, params, newWindow) {
    if (newWindow === undefined) { newWindow = false; }
    if (newWindow) {
        window.open(generateRequestedUrl({
            page : page,
            subpage : subpage,
            params : params
        }), "_blank");
    } else {
        window.location = generateRequestedUrl({
            page : page,
            subpage : subpage,
            params : params
        });
    }
}

function generateAdminRequestedUrl(request) {
    var url = ImpexResources.baseURL + "/index.php";
    var params = [];
    request.mode = "admin";
    if (request.page) { params.push("choice=" + request.page); }
    if (request.subpage) { params.push("subpage=" + request.subpage); }
    if (request.mode) { params.push("mode=" + request.mode); }
    if (request.params) {
        var params2 = [];
        for (var fld in request.params) {
            if (typeof request.params[fld] == "function") { continue; }
            params2.push("s:" + fld.length + ":\"" + fld + "\";s:" + ("" + request.params[fld]).length + ":\"" + request.params[fld] + "\";");
        }
        params.push("params=" + encodeURIComponent("a:" + params2.length + ":{" + params2.join("") + "}"));
    }
    queryString = params.join("&");
    if (params.length > 0) { url += "?" + queryString; }
   return url;
}

function generateRequestedUrl(request) {
    var url = ImpexResources.baseURL + "/index.php";
    var params = [];
    if (request.page) { params.push("choice=" + request.page); }
    if (request.subpage) { params.push("subpage=" + request.subpage); }
    if (request.mode) { params.push("mode=" + request.mode); }
    if (request.params) {
        var params2 = [];
        for (var fld in request.params) {
            if (typeof request.params[fld] == "function") { continue; }
            params2.push("s:" + fld.length + ":\"" + fld + "\";s:" + ("" + request.params[fld]).length + ":\"" + request.params[fld] + "\";");
        }
        params.push("params=" + encodeURIComponent("a:" + params2.length + ":{" + params2.join("") + "}"));
    }
    queryString = params.join("&");
    if (params.length > 0) { url += "?" + queryString; }
   return url;
}

function generateServiceUrl(serviceRequest) {
    var url = ImpexResources.baseURL + "/index.php";
    var params = [];
    if (serviceRequest.admin) {
        params.push("mode=adminservice");
    } else {
        params.push("mode=service");
    }
    params.push("service=" + serviceRequest.service);
    params.push("page=" + serviceRequest.page);
    if (serviceRequest.params) {
        var params2 = [];
        for (var fld in serviceRequest.params) {
            params2.push("s:" + fld.length + ":\"" + fld + "\";s:" + ("" + serviceRequest.params[fld]).length + ":\"" + serviceRequest.params[fld] + "\";");
        }
        params.push("params=a:" + params2.length + ":{" + params2.join("") + "}");
    }
    return url + "?" + params.join("&");
}

function reveal(id) {
    jQuery("#" + id).show("slide", {
        direction : "up"
    }, 400);
}

function hide(id) {
    jQuery("#" + id).hide("slide", {
        direction : "up"
    }, 400);
}

function openFileBrowser(fileControlName) {
    jQuery("input[type='file'][name='" + fileControlName + "']").click();
}

Array.prototype.exists = function(item) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) { return true; }
    }
    return false;
}

Array.prototype.remove = function(item) {
    var ndx = -1;
    for (var i = 0; i < this.length; i++) {
        if (this[i] == item) { ndx = i; }
    }
    if (ndx >= 0) {
        this.splice(ndx, 1);
    }
}
